import React, { FC, useContext } from 'react'
import {
  SelectOptionProps,
  DISPLAY_NAME_OPTION,
  getOptionClassNames,
} from './config'
import { SelectContext } from '../../Select'
import Icon from '../../Icon'

export const Option: FC<SelectOptionProps> = props => {
  const { value, label, disabled, children, index } = props
  const { onSelect, selectedValues, multiple } = useContext(SelectContext)
  const isSelected = selectedValues.includes(value)

  const optionClasses = getOptionClassNames(props, () => {
    return {
      'is-selected': isSelected,
    }
  })

  const handleClick = (
    e: React.MouseEvent,
    value: string,
    isSelected: boolean
  ) => {
    e.preventDefault()
    if (onSelect && !disabled) {
      onSelect(value, isSelected)
    }
  }
  return (
    <li
      key={index}
      className={optionClasses}
      onClick={e => {
        handleClick(e, value, isSelected)
      }}>
      {children || (label ? label : value)}
      {multiple && isSelected && <Icon icon="check" />}
    </li>
  )
}
Option.displayName = DISPLAY_NAME_OPTION

export default Option
